﻿using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using RxxAdmin.Common;
using RxxAdmin.Common.Helper;
using RxxAdmin.IServices;
using RxxAdmin.Model;
using RxxAdmin.Model.Entity;
using RxxAdmin.Model.Logs;
using RxxAdmin.Model.ViewModels;
using RxxAdmin.Services;

namespace RxxAdmin.Api.Controllers.permission;
/// <summary>
/// 用户管理
/// </summary>
public class SysUserController : BaseApiController
{
    private readonly ISysUserService _sysUserService;
    private readonly ISysUserRoleService _sysUserRoleService;
    private readonly ISysRoleService _sysRoleService;
    private readonly IMapper _mapper;

    public SysUserController(ISysUserService sysUserService, ISysUserRoleService sysUserRoleService, ISysRoleService sysRoleService, IMapper mapper)
    {
        _sysUserService = sysUserService;
        _sysUserRoleService = sysUserRoleService;
        _sysRoleService = sysRoleService;
        _mapper = mapper;
    }

    /// <summary>
    /// 获取全部用户分页查询
    /// </summary>
    /// <returns></returns> 
    [HttpGet]
    [OperLog("获取全部用户", OperEnum.Select)]
    public async Task<MessageModel<PageModel<SysUser>>> PageList([FromQuery] SysUserPageIn input)
    {
        if (string.IsNullOrEmpty(input.LoginName) || string.IsNullOrWhiteSpace(input.LoginName))
        {
            input.LoginName = "";
        }
        var users = await _sysUserService.QueryPage(
                    a => a.Status >= 0 && a.LoginName != null && a.LoginName.Contains(input.LoginName),
                    input.PageNum,
                    input.PageSize,
                    " Id desc ");
        for (int i = 0; i < users.dataCount; i++)
        {
            users.data[i].RoleIds = (await _sysUserRoleService.Query()).Where(x => x.UserId == users.data[i].Id).Select(x => x.RoleId).ToList();
            users.data[i].RoleNames = (await _sysRoleService.Query()).Where(x => users.data[i].RoleIds.Contains(x.Id)).Select(x => x.Name).ToList();
        }
        return Success(users.ConvertTo<SysUser>(_mapper));
    }

    /// <summary>
    /// 添加用户
    /// </summary>
    /// <returns></returns> 
    [HttpPost]
    [OperLog("添加用户信息", OperEnum.Insert)]
    public async Task<MessageModel<string>> Add(SysUser input)
    {
        input.LoginPWD = MD5Helper.MD5Encrypt32("123456");
        var bo = await _sysUserService.Add(input);
        foreach (var item in input.RoleIds)
        {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.UserId = (int)bo;
            sysUserRole.RoleId = item;
            var row = await _sysUserRoleService.Add(sysUserRole);
        }
        return bo > 0 ? Success(input?.Id.ObjToString(), "新增成功") : Failed("新增失败");
    }

    /// <summary>
    /// 删除用户
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpDelete("{id}")]
    [OperLog("删除用户信息", OperEnum.Delete)]
    public async Task<MessageModel<string>> Delete(int id)
    {
        var bo = await _sysUserService.DeleteById(id);
        var userRoles = (await _sysUserRoleService.Query()).Where(x => x.UserId == id).ToList();
        var boo = await _sysUserRoleService.DeleteByIds(Array.ConvertAll(userRoles.Select(x => x.Id).ToArray(), Convert.ToString));
        return bo ? Success(id.ObjToString(), "删除成功") : Failed("删除失败");
    }

    /// <summary>
    /// 更新用户
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPut]
    [OperLog("更新用户信息", OperEnum.Update)]
    public async Task<MessageModel<string>> Update(SysUser input)
    {
        var bo = await _sysUserService.Update(input);
        var userRoles = (await _sysUserRoleService.Query()).Where(x => x.UserId == input.Id).ToList();
        var boo = await _sysUserRoleService.DeleteByIds(Array.ConvertAll(userRoles.Select(x => x.Id).ToArray(), Convert.ToString));
        foreach (var item in input.RoleIds)
        {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.UserId = input.Id;
            sysUserRole.RoleId = item;
            var row = await _sysUserRoleService.Add(sysUserRole);
        }
        return bo ? Success(input?.Id.ObjToString(), "更新成功") : Failed("更新失败");
    }
}
